package logic

import (
	"2210a/practice/models/mysql"
	"2210a/practice/models/redisinit"
	"2210a/practice/pkg"
	"context"
	"fmt"

	"2210a/practice/practicerpc/internal/svc"
	"2210a/practice/practicerpc/practicerpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdatePasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdatePasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdatePasswordLogic {
	return &UpdatePasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdatePasswordLogic) UpdatePassword(in *practicerpc.UpdatePasswordRequest) (*practicerpc.UpdatePasswordResponse, error) {
	// todo: add your logic here and delete this line
	var login mysql.User
	mysql.Db.Debug().Where("mobile = ?", in.Mobile).Find(&login)
	if login.ID == 0 {
		return nil, fmt.Errorf("当前用户没注册，请重新注册")
	}
	if in.Password == in.OldPassword {
		return nil, fmt.Errorf("新密码和旧密码不可以一致")
	}
	if in.Password != in.NewPassword {
		return nil, fmt.Errorf("新密码跟确认密码不一致")
	}

	get := redisinit.ClientRedis.Get("codeupdate" + in.Mobile)
	if get.Val() != in.Code {
		return nil, fmt.Errorf("获取短信发送信息错误，请重新输入 ")
	}
	if login.Password != pkg.Md5Encryption(in.OldPassword) {
		return nil, fmt.Errorf("旧密码和原密码不一致")
	}
	login.Password = pkg.Md5Encryption(in.Password)
	mysql.Db.Debug().Model(&login).Updates(&login)
	return &practicerpc.UpdatePasswordResponse{Id: int64(login.ID)}, nil
}
